-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMatrix Exponentiation.cpp
More file actions
61 lines (56 loc) · 1021 Bytes
/
Matrix Exponentiation.cpp
File metadata and controls
61 lines (56 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Solving recurrence relation by matrix exponentiation
f(n) = f(n - 1) + f(n - 2) + 5
f(0) = f(1) = 1
Time Complexity: O(logn)
*/
#include <iostream>
#include <string.h>
void multiply(int a[3][3], int b[3][3])
{
int res[3][3];
memset(res, 0, sizeof(res));
for(int i = 0; i < 3; i ++) {
for(int j = 0; j < 3; j ++) {
for(int k = 0; k < 3; k ++) {
res[i][j] += (a[i][k] * b[k][j]);
}
}
}
for(int i = 0; i < 3; i ++) {
for(int j = 0; j < 3; j ++) {
a[i][j] = res[i][j];
}
}
}
void binary_exp(int a[3][3], int n)
{
int res[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
while(n > 0) {
if(n & 1) {
multiply(res, a);
}
multiply(a, a);
n >>= 1;
}
for(int i = 0; i < 3; i ++) {
for(int j = 0; j < 3; j ++) {
a[i][j] = res[i][j];
}
}
}
int main()
{
int n;
std::cin >> n;
if(n <= 2) {
std::cout << "1";
}
else {
int a[3][3] = {{1, 1, 5}, {1, 0, 0}, {0, 0, 1}};
binary_exp(a, n - 2);
int d = a[0][0] * 1 + a[0][1] * 1 + a[0][2];
std::cout << d;
}
return 0;
}